package com.ruoyi.common.utils.file;

import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * 下载工具类
 *
 * @Author: Jamnsin
 * @Date: 2019/12/13 11:15 上午
 */
@Slf4j
public class DownloadUtils {

    /**
     * 网络url 文件下载本地
     *
     * @param file
     * @param remoteFileUrl
     */
    public static void remoteDownload(File file, String remoteFileUrl) {
        URL url = null;
        HttpURLConnection uc = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            url = new URL(remoteFileUrl);
            uc = (HttpURLConnection) url.openConnection();
            //设置是否要从 URL 连接读取数据，默认为true
            uc.setDoInput(true);

            byte[] buffer = new byte[4 * 1024];
            int byteRead = -1;

            inputStream = uc.getInputStream();

            //打印文件长度
            log.debug(file.getName() + "，file size is:" + uc.getContentLength());
            outputStream = new FileOutputStream(file);

            while (true) {
                if (!((byteRead = (inputStream.read(buffer))) != -1)) {
                    break;
                }
                outputStream.write(buffer, 0, byteRead);
            }

            outputStream.flush();
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
//            throw new HttpRequestException("文件服务器请求异常，请联系管理员");
        } catch (FileNotFoundException e) {
            throw new BusinessException(RspEnmu.FILE_NOT_FOUND, e);
        } catch (IOException e) {
            throw new BusinessException(RspEnmu.FILE_PROCESS_ERR, e);
        } finally {
            IOUtils.closeQuietly(inputStream, outputStream);
        }
    }

    /**
     * 单文件下载
     *
     * @param filePath
     */
    public static void downLoad(String filePath) {

        HttpServletResponse response = ServletUtils.getResponse();
        HttpServletRequest request = ServletUtils.getRequest();

        File file = new File(filePath);
        if (!file.exists()) {
            log.error("文件不存在，{}", filePath);
            throw new BusinessException(RspEnmu.FILE_NOT_FOUND, filePath);
        }

        BufferedInputStream br = null;
        OutputStream out = null;
        try {
            response.reset(); // 非常重要
            response.setHeader("Content-Disposition", "attachment; filename=" + FileUtils.setFileDownloadHeader(request, file.getName()));
            response.addHeader("Content-Length", String.valueOf(file.length()));
            response.setContentType("application/octet-stream; charset=UTF-8");

            byte[] buf = new byte[1024];
            int len = 0;

            br = new BufferedInputStream(new FileInputStream(file));
            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (FileNotFoundException e) {
            log.error("文件不存在：", e.getMessage());
            throw new BusinessException(RspEnmu.FILE_NOT_FOUND, e);
        } catch (IOException e) {
            log.error("文件IO 异常：", e.getMessage());
            throw new BusinessException(RspEnmu.FILE_PROCESS_ERR, e);
        } finally {
            IOUtils.closeQuietly(br, out);
        }
    }

    /**
     * 文件压缩下载
     *
     * @param fileList
     * @throws IOException
     */
    public static void zipDownload(List<File> fileList) throws IOException {

        HttpServletResponse response = ServletUtils.getResponse();
        HttpServletRequest request = ServletUtils.getRequest();

        String fileName = "风险评估报告_" + DateUtils.dateTimeNow("yyyyMMddHHmm") + ".zip";

        /** 设置response的header */
        response.reset();
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + FileUtils.setFileDownloadHeader(request, fileName));

        /** 调用工具类，下载zip压缩包 */
        ZipUtils.toZip(fileList, response.getOutputStream());
    }
}
